import React,{Component} from "react";
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  Image,
  TouchableWithoutFeedback,
  Platform,
  PermissionsAndroid, Modal,
} from "react-native";
import CustomerHeader from "../../widget/customerHeader";
import  LinearGradient from 'react-native-linear-gradient';
import * as RootNavigation from '../../../App';
import ActionSheet from "react-native-actionsheet";
import { launchCamera, launchImageLibrary } from "react-native-image-picker";
import Loading from "../../widget/Loading";
import NetUtil from "../../net/net_util";
import Toast from "../../widget/Toast";
import { width } from "../../util/apdater_util";
import ImageViewer from "react-native-image-zoom-viewer";

export default class PublishTopic extends Component{
  constructor(props) {
    super(props);
    this.state={
      isImageViewer:false,
      imageIndex:0,
      previewImageList:[],
      photos:[],
      content:'',
      topic:null,
    }
  }

  selectTopic(){
    let _this=this
    RootNavigation.navigate('SelectTopic',{callback:(data)=>{
        _this.setState({topic:data})
    }})
  }

  //吊起选择框
  async _imagePicker(){
    if(Platform.OS=='android'){
      this.requestPermission();
    }
    let newPhotos = this.state.photos

    if(newPhotos.length>=3){
      Toast.show("图片最多为3张")
      return
    }
    this.ActionSheet.show()
  }

  //权限
  requestPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: '申请读写手机存储权限',
          message:
            '一个很牛逼的应用想借用你的摄像头，' +
            '然后你就可以拍出酷炫的皂片啦。',
          buttonNeutral: '等会再问我',
          buttonNegative: '不行',
          buttonPositive: '好吧',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('现在你获得摄像头权限了');
      } else {
        console.log('用户并不给你');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  //相机拍摄
  selectphotograph(){
    let newPhotos = this.state.photos
    if(newPhotos.length===3){
      Toast.add('最多为三张图片')
      return
    }
    launchCamera({mediaType:'photo',quality:1,selectionLimit:1},({assets})=>{
      if(assets){
        let path=assets[0].uri;
        this.uploadImg(path)
      }
    })
  }

  //相册选择
  selectFromAlbum(){
    launchImageLibrary({mediaType:'photo',quality:1,selectionLimit:1},({assets})=>{
      if(assets){
        let path=assets[0].uri;
        this.uploadImg(path)
      }
    })
  }

  /*上传图片*/
  uploadImg(url){
    Loading.show('正在上传');
    NetUtil.upload('base/upload/file',{path:url},(res)=>{
      Loading.hide()
      if(res.code==200){
        let photos=this.state.photos;
        photos.push(res.data)
        this.setState({photos:photos})
      }
    })
  }

  /**删除图片*/
  deletePhoto(index){
    let photos=this.state.photos;
    photos.splice(index,1);
    this.setState({photos:photos})
  }
  /*预览图片*/
  previewImage(index){
    let photos=this.state.photos;
    let imageList=photos.map((img,idex)=>{
      return {url:img}
    })
    this.setState(
      {imageIndex:index,
        isImageViewer:true,
        previewImageList:imageList})
  }

  /*发布*/
  submit(){
    if(!this.state.content){
      Toast.add('请输入内容')
      return
    }
    let param={
      content:this.state.content,
      images:this.state.photos,
      topicId:this.state.topic?this.state.topic.id:''
    }
    Loading.show()
    NetUtil.postJson('trend/dynamic/create',param,(res)=>{
      Loading.hide()
      if(res.code==200){
        Toast.add('发布成功')
        setTimeout(()=>{
          this.props.navigation.pop()
        },1500)
      }
      else {
        Toast.add(res.msg)
      }
    })
  }

  render(){
    return (
      <View style={{flex:1,backgroundColor:'#fff'}}>
        <CustomerHeader title={'发布动态'} leftOnPress={()=>{this.props.navigation.pop()}}>
          <TouchableWithoutFeedback onPress={this.submit.bind(this)}>
            <LinearGradient colors={['#e79c58','#f8da85']}  style={styles.publish}>
              <Text style={styles.publishTxt}>发布</Text>
            </LinearGradient>
          </TouchableWithoutFeedback>
        </CustomerHeader>
        <View style={styles.header}>
          <TextInput style={{height:240}} value={this.state.content} onChangeText={(text)=>{this.setState({content:text})}} multiline={true} placeholder={'来说说你的方案吧...'}></TextInput>
          <View style={styles.imgList}>
            {this.state.photos.map((photo,index)=>{
              return (
                <View style={[styles.imgBox,{marginRight:index<2?10:0}]} key={'photo'+index}>
                  <TouchableWithoutFeedback onPress={this.previewImage.bind(this,index)}>
                    <Image style={{flex:1,borderRadius:4}} source={{uri:photo}}></Image>
                  </TouchableWithoutFeedback>
                  <View style={styles.delete}>
                    <TouchableWithoutFeedback onPress={()=>{this.deletePhoto(index)}}>
                      <Image style={{width:20,height:20}} source={require('../../img/photo_delete_icon.png')}></Image>
                    </TouchableWithoutFeedback>
                  </View>
                </View>
              )
            })}
            {this.state.photos.length>=3?null:(
              <TouchableWithoutFeedback onPress={()=>{this._imagePicker()}}>
                <View style={styles.upload}>
                  <Image style={styles.icon} source={require('../../img/photo.png')}></Image>
                  <Text style={styles.iconTitle}>上传图片</Text>
                </View>
              </TouchableWithoutFeedback>
            )}
          </View>
        </View>
          <View style={styles.footer}>
            <Image style={styles.selectIcon} source={require('../../img/topic_black_icon.png')}></Image>
            {!this.state.topic?(
              <TouchableWithoutFeedback onPress={this.selectTopic.bind(this)}>
                <View style={styles.selectTopic}>
                  <Text style={{color:'#1C1C1C',fontSize:14}}>选择话题</Text>
                  <Image style={{width:6,height:12,marginRight:15}} source={require('../../img/arrow_right_icon.png')}></Image>
                </View>
              </TouchableWithoutFeedback>
            ):(
              <View style={styles.bar}>
                <Text style={{color:'#3CA1FD',fontSize:11}}>{this.state.topic.name}</Text>
                <TouchableWithoutFeedback onPress={()=>{this.setState({topic:null})}}>
                  <Image style={{width:9,height:9,marginLeft:8}} source={require('../../img/close_blue_icon.png')}></Image>
                </TouchableWithoutFeedback>
              </View>
            )}
          </View>
        <ActionSheet
          ref={o => this.ActionSheet = o}
          title={'请选择照片类型'}
          options={['选择相册', '拍照', '取消']}
          cancelButtonIndex={2}
          destructiveButtonIndex={1}
          onPress={(index) => { if(index===0){this.selectFromAlbum()}else if(index===1){this.selectphotograph()}}}
        />
        {this.state.isImageViewer?(
          <Modal transparent={true} visible={true} onRequestClose={()=> {
            this.setState({
              isImageViewer: false,
            });
          }}>
            <ImageViewer enableSwipeDown
                         enableImageZoom={true}
                         onClick={() => { // 图片单击事件
                           this.setState({
                             isImageViewer: false,
                           });
                         }}
                         imageUrls={this.state.previewImageList}
                         onCancel={()=> {
                           this.setState({
                             isImageViewer: false,
                           });
                         }}
                         index={this.state.imageIndex}
                         saveToLocalByLongPress={false}/>
          </Modal>
        ):null}
        <Loading></Loading>
        <Toast></Toast>
      </View>
    )
  }
}

const styles=StyleSheet.create({
  icon:{
    width: 30,
    height:30
  },
  iconTitle:{
    color:'#B7B7B7',
    fontSize: 12
  },
  publish:{
    width:43,
    height:25,
    borderRadius: 22.5,
    marginRight:14
  },
  publishTxt:{
    color:'#fff',
    fontSize: 13,
    lineHeight:25,
    textAlign:'center'
  },
  header:{
    height:370,
    backgroundColor:'#fff',
    paddingVertical:16,
    paddingHorizontal:15,
  },
  footer:{
    flexDirection:'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginTop:20,
    marginLeft:15
  },
  selectIcon:{
    width:15,
    height:15,
    marginRight: 7
  },
  bar:{
    backgroundColor: '#F4F9FD',
    height:25,
    borderRadius:12.5,
    flexDirection: 'row',
    justifyContent:'flex-start',
    alignItems:'center',
    marginLeft: 6,
    paddingHorizontal: 10
  },
  selectTopic:{
    flex:1,
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center'
  },
  imgList:{
    flexDirection: 'row',
    justifyContent:'flex-start',
    flexWrap:'nowrap',
    alignItems:'center'
  },
  upload:{
    width:(width-50)/3.0,
    height:(width-50)/3.0,
    justifyContent:'center',
    alignItems:'center',
    borderStyle:'dashed',
    borderWidth:1,
    borderColor:'#DADADA',
    borderRadius:7
  },
  imgBox:{
    width:(width-50)/3.0,
    height:(width-50)/3.0,
    borderRadius:4
  },
  delete:{
    position:'absolute',
    width:20,
    height:20,
    borderRadius:10,
    top:-10,
    right:-8,
    backgroundColor:'#fff',
    zIndex: 99999
  }
})
